package com.hsogoo.avatar.executor;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.registry.AbstractAvatarRegistry;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/10/24.
 */
@Slf4j
public class ThreadPoolExecutorFactory extends AbstractExecutorFactory {

    @Override
    public AvatarExecutor newExecutor(Target target, String name) {
        final ThreadPoolExecutor executor = new ThreadPoolExecutor(
                coreWorkers(target),
                maxWorkers(target),
                120L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity(target)),
                threadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy());

        return new AvatarExecutor() {

            @Override
            public void execute(Runnable r) {
                executor.execute(r);
            }

            @Override
            public void shutdown() {
                log.warn("ThreadPoolExecutorFactory#{} shutdown.", executor);
                executor.shutdownNow();
            }
        };
    }
}
